import {ref} from 'vue'
import {listByParentCode} from "@/api/nongjt/area.js"
export function areaSelect() {
    //省份列表
    const provinceList = ref([])
    //市列表
    const cityList = ref([])
    //区县列表
    const areaList = ref([])
    //街道列表
    const streetList = ref([])
    //初始化省
    const initProvinceList = () => {
        console.log('初始化省份列表')
        // 尝试不同的方式获取省份数据
        listByParentCode().then(res => {
            console.log('省份列表完整响应(无参数):', res)
            console.log('省份列表数据(无参数):', res.data)
            console.log('省份列表数据长度(无参数):', res.data ? res.data.length : 'data is null/undefined')
            if (res.data && res.data.length > 0) {
                provinceList.value = res.data
            } else {
                // 如果无参数获取不到数据，尝试使用parentCode=0
                listByParentCode({parentCode: 0}).then(res2 => {
                    console.log('省份列表完整响应(parentCode=0):', res2)
                    console.log('省份列表数据(parentCode=0):', res2.data)
                    provinceList.value = res2.data || []
                }).catch(error => {
                    console.error('获取省份列表失败(parentCode=0):', error)
                })
            }
        }).catch(error => {
            console.error('获取省份列表失败(无参数):', error)
        })
    }
    //选择省改变
    const provinceChange = (parentCode) => {
        console.log('选择省份，parentCode:', parentCode)
        return listByParentCode({parentCode}).then(res => {
            console.log('市级数据:', res)
            cityList.value = res.data || []
        }).catch(error => {
            console.error('获取市级数据失败:', error)
        })
    }
    //选择市改变
    const cityChange = (parentCode) => {
        console.log('选择市，parentCode:', parentCode)
        return listByParentCode({parentCode}).then(res => {
            console.log('区级数据:', res)
            areaList.value = res.data || []
        }).catch(error => {
            console.error('获取区级数据失败:', error)
        })
    }
    //选择区改变
    const areaChange = (parentCode) => {
        console.log('选择区，parentCode:', parentCode)
        return listByParentCode({parentCode}).then(res => {
            console.log('街道数据:', res)
            streetList.value = res.data || []
        }).catch(error => {
            console.error('获取街道数据失败:', error)
        })
    }
    //重置
    const resetAreaList = () => {
        cityList.value = []
        areaList.value = []
        streetList.value = []
    }
    return {
        provinceList,
        cityList,
        areaList,
        streetList,
        initProvinceList,
        provinceChange,
        cityChange,
        areaChange,
        resetAreaList
    }
}